package com.sunlake.spring.main.model.auth.controller;

import com.sunlake.spring.main.common.response.R;
import com.sunlake.spring.main.common.utils.JwtTokenUtil;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 * 处理登录、注销和刷新令牌的请求
 * @author by liuhanzhi
 */
@RestController
@RequestMapping("/auth")
public class AuthController1 {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    /**
     * 登录接口
     * 注意：这里仅作为示例，实际项目中需要调用用户服务验证用户名和密码
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginRequest loginRequest) {
        // 示例：这里简化了用户验证逻辑，实际项目中应调用用户服务进行验证
        // 假设用户ID为1，用户名为loginRequest.getUsername()
        Long userId = 1L;
        String username = loginRequest.getUsername();
        // 生成JWT令牌和刷新令牌
        String token = jwtTokenUtil.generateToken(userId, username);
        String refreshToken = jwtTokenUtil.generateRefreshToken(userId, username);

        // 构建响应数据
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("refreshToken", refreshToken);
        tokenMap.put("tokenType", "Bearer");

        return R.ok(200,"登录成功",tokenMap);
    }

    /**
     * 刷新令牌接口
     */
    @PostMapping("/refresh")
    public R refreshToken(@RequestBody RefreshTokenRequest request) {
        String refreshToken = request.getRefreshToken();

        // 刷新令牌
        String newToken = jwtTokenUtil.refreshToken(refreshToken);

        if (newToken != null) {
            Map<String, String> tokenMap = new HashMap<>();
            tokenMap.put("token", newToken);
            tokenMap.put("tokenType", "Bearer");
            return R.ok(200,"刷新令牌成功",tokenMap);
        } else {
            return R.error(401,"刷新令牌无效或已过期");
        }
    }
    /**
     * 注销接口
     */
    @PostMapping("/logout")
    public R logout(@RequestParam Long userId) {
        jwtTokenUtil.logout(String.valueOf(userId));
        return R.ok(200,"注销成功");
    }

    // 登录请求类
    static class LoginRequest {
        private String username;
        private String password;

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }
    // 刷新令牌请求类
    @Setter
    @Getter
    static class RefreshTokenRequest {
        private String refreshToken;
    }
}